import socket
import threading
import struct
import pickle
from .gui.main_window import MainWindow

class PCClient:
    def __init__(self, host='localhost', port=9999):
        self.host = host
        self.port = port
        self.socket = None
        self.is_connected = False
        self.gui = MainWindow()
        self.cameras = {}  # 存储摄像头信息
        self.current_camera = None
        self.setup_gui()

    def setup_gui(self):
        """设置GUI回调"""
        self.gui.set_connect_callback(self.toggle_connection)
        self.gui.set_camera_select_callback(self.on_camera_selected)

    def toggle_connection(self):
        """切换连接状态"""
        if not self.is_connected:
            self.connect()
        else:
            self.disconnect()

    def connect(self):
        """连接到服务器"""
        try:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.connect((self.host, self.port))
            
            # 发送客户端类型
            self.socket.send('pc'.encode().ljust(16))
            
            self.is_connected = True
            self.gui.update_status("已连接到服务器")
            
            # 启动接收数据的线程
            receive_thread = threading.Thread(target=self.receive_data)
            receive_thread.start()
            
        except Exception as e:
            self.gui.update_status(f"连接失败: {str(e)}")

    def disconnect(self):
        """断开连接"""
        self.is_connected = False
        if self.socket:
            self.socket.close()
        self.cameras.clear()
        self.current_camera = None
        self.gui.update_status("已断开连接")

    def on_camera_selected(self, camera_id):
        """处理摄像头选择"""
        self.current_camera = camera_id
        self.gui.update_status(f"正在显示设备 {self.cameras.get(camera_id, '未知')} 的画面")

    def handle_camera_info(self, info):
        """处理摄像头信息"""
        if info['action'] == 'new':
            self.cameras[info['id']] = info['ip']
            self.gui.add_camera(info['id'], info['ip'])
            self.gui.update_status(f"新设备连接: {info['ip']}")
        elif info['action'] == 'remove':
            if info['id'] in self.cameras:
                self.cameras.pop(info['id'])
                self.gui.remove_camera(info['id'])
                self.gui.update_status(f"设备断开连接: {info['ip']}")
                if self.current_camera == info['id']:
                    self.current_camera = None

    def receive_data(self):
        """接收数据"""
        data = b""
        payload_size = struct.calcsize("L")

        while self.is_connected:
            try:
                while len(data) < payload_size:
                    data += self.socket.recv(4096)
                packed_msg_size = data[:payload_size]
                data = data[payload_size:]
                msg_size = struct.unpack("L", packed_msg_size)[0]

                while len(data) < msg_size:
                    data += self.socket.recv(4096)
                frame_data = data[:msg_size]
                data = data[msg_size:]

                # 解析数据
                received_data = pickle.loads(frame_data)
                
                # 处理不同类型的数据
                if isinstance(received_data, dict) and received_data.get('type') == 'camera_info':
                    self.handle_camera_info(received_data)
                else:
                    # 视频帧数据
                    self.gui.update_frame(received_data)
            except:
                break

        self.disconnect()

    def run(self):
        """运行客户端"""
        self.gui.run()

if __name__ == "__main__":
    client = PCClient()
    client.run() 